import { useState, useEffect } from 'react'
import { View, Text, Button, Image } from '@tarojs/components'
import Taro, { useShareAppMessage } from '@tarojs/taro'
import './index.scss'
import mbtiQuestions from './questions.json'

// 获取当前主题
const getCurrentTheme = () => {
  try {
    const savedTheme = Taro.getStorageSync('user-theme-preference')
    if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
      return savedTheme
    }
    return 'mint' // 默认主题
  } catch (e) {
    console.error('获取主题失败', e)
    return 'mint' // 出错时返回默认主题
  }
}

const MBTITest = () => {
  const [showStartPage, setShowStartPage] = useState(true)
  const [currentQuestion, setCurrentQuestion] = useState(0)
  const [answers, setAnswers] = useState({})
  const [showResult, setShowResult] = useState(false)
  const [result, setResult] = useState('')
  const [resultExplanation, setResultExplanation] = useState('')
  const [currentTheme, setCurrentTheme] = useState('mint')
  const [dimensionScores, setDimensionScores] = useState({
    E: 0,
    I: 0,
    S: 0,
    N: 0,
    T: 0,
    F: 0,
    J: 0,
    P: 0
  })

  // 初始化时获取主题
  useEffect(() => {
    const theme = getCurrentTheme()
    setCurrentTheme(theme)

    // 定时检查主题变化
    const updateTheme = () => {
      const newTheme = getCurrentTheme()
      if (newTheme !== currentTheme) {
        setCurrentTheme(newTheme)
      }
    }

    const interval = setInterval(updateTheme, 5000)
    return () => clearInterval(interval)
  }, [currentTheme])

  // 配置分享信息
  useShareAppMessage(() => {
    let title = '揭秘你的性格密码，发现真实的自己！'
    let path = '/pages-mbti/index'

    // 如果已有测试结果，则在标题中显示
    if (showResult && result) {
      title = `我的MBTI类型是${result}，解锁你的性格潜能，一测便知！`
      path = `/pages-mbti/index`
    }

    return {
      title,
      path,
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/mbti.jpg' // 替换为实际的分享图片
    }
  })

  // 开始测试
  const startTest = () => {
    setShowStartPage(false)
  }

  // 进度计算
  const progress = ((currentQuestion + 1) / mbtiQuestions.length) * 100

  // 选择答案
  const selectOption = (dimension, value) => {
    setAnswers({
      ...answers,
      [currentQuestion]: { dimension, value }
    })

    // 如果是最后一题，选择后直接完成测试
    if (currentQuestion === mbtiQuestions.length - 1) {
      // 设置状态并延迟调用calculateResult，确保状态已更新
      setTimeout(() => calculateResult(), 300)
    } else {
      // 自动进入下一题
      setCurrentQuestion(currentQuestion + 1)
    }
  }

  // 上一题
  const prevQuestion = () => {
    if (currentQuestion > 0) {
      setCurrentQuestion(currentQuestion - 1)
    }
  }

  // 下一题
  const nextQuestion = () => {
    if (currentQuestion < mbtiQuestions.length - 1) {
      setCurrentQuestion(currentQuestion + 1)
    } else {
      calculateResult()
    }
  }

  // 计算MBTI结果
  const calculateResult = () => {
    const scores = { E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 }

    Object.values(answers).forEach((answer) => {
      scores[answer.value]++
    })

    // 设置维度得分用于展示
    setDimensionScores(scores)

    const mbtiResult = [
      scores.E > scores.I ? 'E' : 'I',
      scores.S > scores.N ? 'S' : 'N',
      scores.T > scores.F ? 'T' : 'F',
      scores.J > scores.P ? 'J' : 'P'
    ].join('')

    setResult(mbtiResult)
    setResultExplanation(getResultExplanation(mbtiResult))
    setShowResult(true)
  }

  // 获取结果解释
  const getResultExplanation = (mbtiType) => {
    const explanations = {
      INFP: '理想主义者：富有想象力和敏感性，追求内在和谐与个人价值观的实现。',
      INFJ: '提倡者：有远见的理想主义者，注重内在思考和价值观，追求帮助他人。',
      INTJ: '建筑师：独立思考的战略家，擅长系统思维，追求不断完善。',
      INTP: '逻辑学家：创新的发明家，热爱理论和抽象，追求逻辑与洞察。',
      ISFP: '探险家：灵活而魅力四射的艺术家，热爱尝试新体验。',
      ISFJ: '守卫者：温暖细致的守护者，乐于服务他人，组织能力强。',
      ISTJ: '物流师：实际且注重事实的人，可靠、重视传统与秩序。',
      ISTP: '鉴赏家：大胆而实际的实验者，擅长工具和机械，行动导向。',
      ENFP: '活动家：热情洋溢的创意思想家，始终看到可能性和潜力。',
      ENFJ: '主人公：富有魅力和鼓舞人心的领导者，对他人影响力大。',
      ENTP: '辩论家：聪明且好奇的思想家，喜欢智力挑战和辩论。',
      ENTJ: '指挥官：大胆、果断的领导者，有建设性和实现目标的决心。',
      ESFP: '表演者：自发的、精力充沛且热爱生活的人，享受表演。',
      ESFJ: '执政官：关心他人的助手和提供者，重视和谐与合作。',
      ESTJ: '总经理：高效的管理者，喜欢按规章制度办事和维持秩序。',
      ESTP: '企业家：聪明、精力充沛的人，享受冒险和物质享受。'
    }

    return explanations[mbtiType] || '无法获取详细解释，请重新测试。'
  }

  // 重新测试
  const retakeTest = () => {
    setShowStartPage(true)
    setCurrentQuestion(0)
    setAnswers({})
    setShowResult(false)
    setResult('')
    setResultExplanation('')
    setDimensionScores({ E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 })
  }

  // 查看详细说明
  const viewDetail = () => {
    Taro.navigateTo({
      url: `/pages-mbti/detail?result=${result}`
    })
  }

  // 计算维度的百分比
  const calculatePercentage = (value, total) => {
    if (total === 0) return 0
    return Math.round((value / total) * 100)
  }

  return (
    <View className={`mbti-page theme-${currentTheme}`}>
      {showStartPage ? (
        <View className='start-page'>
          {/* Logo区域 */}
          <Image
            className='logo'
            src='https://example.com/your-logo.png' // 替换为实际的logo URL
            mode='widthFix'
          />

          {/* 标题区域 */}
          <Text className='title'>MBTI性格测试</Text>
          <Text className='subtitle'>50道测评题，一探你的性格类型</Text>

          {/* 开始测试按钮 */}
          <Button className='start-btn' onClick={startTest}>
            开始测试
          </Button>

          {/* 底部提示 */}
          <Text className='privacy-tip'>测试结果仅供参考</Text>
        </View>
      ) : !showResult ? (
        <View className='question-container'>
          {/* 进度条 */}
          <View className='progress-bar-container'>
            <View className='progress-bar' style={{ width: `${progress}%` }} />
          </View>

          {/* 题号和题目 */}
          <Text className='question-number'>
            问题 {currentQuestion + 1}/{mbtiQuestions.length}
          </Text>
          <Text className='question-text'>{mbtiQuestions[currentQuestion].text}</Text>

          {/* 选项 */}
          <View className='options-container'>
            {mbtiQuestions[currentQuestion].options.map((option, index) => (
              <Button
                key={index}
                className={`option-btn ${answers[currentQuestion]?.value === option.value ? 'selected' : ''}`}
                onClick={() => selectOption(mbtiQuestions[currentQuestion].dimension, option.value)}>
                <Text className='option-text'>
                  {option.label}. {option.text}
                </Text>
              </Button>
            ))}
          </View>

          {/* 导航按钮 */}
          <View className='nav-buttons'>
            <Button className='nav-btn prev-btn' onClick={prevQuestion} disabled={currentQuestion === 0}>
              上一题
            </Button>
            <Button className='nav-btn next-btn' onClick={nextQuestion} disabled={!answers[currentQuestion]}>
              {currentQuestion === mbtiQuestions.length - 1 ? '完成' : '下一题'}
            </Button>
          </View>
        </View>
      ) : (
        <View className='result-container'>
          <Text className='result-type'>你的类型：{result}</Text>
          <Text className='result-explanation'>{resultExplanation}</Text>

          {/* 维度表格 */}
          <View className='dimension-table'>
            <View className='table-row table-header'>
              <View className='table-cell'>维度</View>
              <View className='table-cell'>得分</View>
              <View className='table-cell'>占比</View>
              <View className='table-cell'>类型</View>
            </View>

            {/* E-I 维度 */}
            <View className='table-row'>
              <View className='table-cell dimension-name'>E-I</View>
              <View className='table-cell'>
                {dimensionScores.E}-{dimensionScores.I}
              </View>
              <View className='table-cell'>
                <View className='percentage-bar'>
                  <View
                    className='percentage-fill e-fill'
                    style={{
                      width: `${calculatePercentage(dimensionScores.E, dimensionScores.E + dimensionScores.I)}%`
                    }}
                  />
                </View>
              </View>
              <View className='table-cell dimension-result'>{result[0]}</View>
            </View>

            {/* S-N 维度 */}
            <View className='table-row'>
              <View className='table-cell dimension-name'>S-N</View>
              <View className='table-cell'>
                {dimensionScores.S}-{dimensionScores.N}
              </View>
              <View className='table-cell'>
                <View className='percentage-bar'>
                  <View
                    className='percentage-fill s-fill'
                    style={{
                      width: `${calculatePercentage(dimensionScores.S, dimensionScores.S + dimensionScores.N)}%`
                    }}
                  />
                </View>
              </View>
              <View className='table-cell dimension-result'>{result[1]}</View>
            </View>

            {/* T-F 维度 */}
            <View className='table-row'>
              <View className='table-cell dimension-name'>T-F</View>
              <View className='table-cell'>
                {dimensionScores.T}-{dimensionScores.F}
              </View>
              <View className='table-cell'>
                <View className='percentage-bar'>
                  <View
                    className='percentage-fill t-fill'
                    style={{
                      width: `${calculatePercentage(dimensionScores.T, dimensionScores.T + dimensionScores.F)}%`
                    }}
                  />
                </View>
              </View>
              <View className='table-cell dimension-result'>{result[2]}</View>
            </View>

            {/* J-P 维度 */}
            <View className='table-row'>
              <View className='table-cell dimension-name'>J-P</View>
              <View className='table-cell'>
                {dimensionScores.J}-{dimensionScores.P}
              </View>
              <View className='table-cell'>
                <View className='percentage-bar'>
                  <View
                    className='percentage-fill j-fill'
                    style={{
                      width: `${calculatePercentage(dimensionScores.J, dimensionScores.J + dimensionScores.P)}%`
                    }}
                  />
                </View>
              </View>
              <View className='table-cell dimension-result'>{result[3]}</View>
            </View>
          </View>

          {/* 操作按钮 */}
          <View className='action-buttons'>
            <Button className='action-btn share-btn' openType='share'>
              分享结果
            </Button>
            <Button className='action-btn retake-btn' onClick={retakeTest}>
              重新测试
            </Button>
          </View>

          {/* 查看详细说明按钮 */}
          <Button className='detail-btn' onClick={viewDetail}>
            查看详细说明
          </Button>

          {/* 底部提示 */}
          <Text className='privacy-tip'>测试结果仅供参考</Text>
        </View>
      )}
    </View>
  )
}

export default MBTITest
